import React from 'react';
import { Spin, Space, Button, DatePicker, Row, Col, Tooltip } from 'antd';
import moment from 'moment';

import { QuestionCircleOutlined } from '#/utils/antdIcons';
import { TRDefault } from '@/components/index.js';
import { useTRState, TjSelect, TjChart, TjTable } from '@/pages/ETrade/components';

import {
  queryPriceSpaceDiff,
  queryPriceDiffReasonAnalyse,
  queryPriceSpaceAndClearPrice,
} from '../services';
import { getChildren } from './children';
import styles from './index.less';
import { useThemeChange } from '@/hooks';

const defaultForm = (power) => {
  const stations = power?.[0]?.children || [];
  return {
    stations,
    date: moment().add(-1, 'day'),
    provinceId: power?.[0]?.provinceId || null,
    marketId: power?.[0]?.value || null,
    stationId: stations?.[0]?.value || null,
  };
};

export default ({ power }) => {
  const [state, setState] = useTRState({
    // 表单
    ...defaultForm(power),
    // 数据
    loading: true,
    rendList: [], // 循环渲染
    allData: {},
  });
  const { theme } = useThemeChange();

  React.useEffect(() => {
    _onFinish();
  }, []);

  React.useEffect(() => {
    setTimeout(() => {
      const rendList = getChildren(state.allData);
      setState({
        rendList,
      });
    }, 1);
  }, [theme]);

  const fetch = async (params) => {
    setState({ loading: true });
    // ！顺序勿动,向后添加
    const resList = await Promise.all([
      queryPriceSpaceDiff(params),
      queryPriceDiffReasonAnalyse(params),
      queryPriceSpaceAndClearPrice(params),
    ]);
    const rendList = getChildren(resList);
    setState({
      allData: resList,
      rendList,
      loading: false,
    });
  };

  /** methods */
  const onChangeRegion = (region) => {
    // 改变省份
    const provinceId = region.provinceId;
    const marketId = region.value;
    const stations = region?.children || [];
    const stationId = stations?.[0]?.value || null;
    setState({
      provinceId,
      marketId,
      stations,
      stationId,
    });
  };

  const _onFinish = () => {
    // 查询
    const { provinceId, stationId, date } = state;
    const formValues = {
      provinceId,
      stationId,
      date: date.format('YYYY-MM-DD'),
    };
    fetch(formValues);
  };

  const _onReset = () => {
    // 重置
    const _def = defaultForm(power);
    state.date = _def.date;
    state.provinceId = _def.provinceId;
    state.marketId = _def.marketId;
    state.stationId = _def.stationId;
    setState({
      ..._def,
    });
    _onFinish();
  };

  /** render */
  const _renderMain = () => {
    if (state.loading) return null;
    if (!state.rendList?.length) return <TRDefault type="empty" />;
    return (
      <Row gutter={[24, 24]}>
        {state.rendList.map((item) => (
          <Col span={12} key={item.title}>
            <div className={styles.title}>
              <div>{item.title}</div>
              {!!item.tooltip && (
                <Tooltip placement="topLeft" title={item.tooltip}>
                  <QuestionCircleOutlined className={styles.ques} />
                </Tooltip>
              )}
            </div>
            <div>
              {item.type === 'table' && <TjTable {...item.props} />}
              {item.type === 'chart' &&
                (!!item.props?.option ? (
                  <TjChart style={{ height: 300 }} {...item.props} />
                ) : (
                  <TRDefault type="emptysm" />
                ))}
            </div>
          </Col>
        ))}
      </Row>
    );
  };
  return (
    <Spin wrapperClassName={styles.spin} spinning={state.loading}>
      <div className={styles.container}>
        <div className={styles.head}>
          <Space size={16} wrap>
            <TjSelect
              style={{ width: 200 }}
              value={state.marketId}
              options={power}
              showSearch
              onChange={(v, opt) => onChangeRegion(opt)}
            />
            <TjSelect
              style={{ width: 200 }}
              value={state.stationId}
              options={state.stations}
              showSearch
              onChange={(stationId) => setState({ stationId })}
            />
            <DatePicker
              style={{ width: 160 }}
              value={moment(state.date)}
              format={'YYYYMMDD'}
              allowClear={false}
              onChange={(date) => setState({ date })}
            />
            <Space size={16}>
              <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
                查询
              </Button>
              <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
                重置
              </Button>
            </Space>
          </Space>
        </div>
        <div className={styles.main}>{_renderMain()}</div>
      </div>
    </Spin>
  );
};
